<script setup>
import { ref, toRefs, reactive, computed, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import StringOrNumber from '../components/StringOrNumber.vue';
import CreateOrEditFrame from '../components/CreateOrEditFrame.vue';
import { listHandler } from '../../api/Generic'
import { deleteTableRow, object2List, list2Object  } from '../../utils/utils';
import Table from '../components/Table.vue';
import DialogYaml from '../components/DialogYaml.vue'
import { obj2Yaml } from '../../utils/utils';
import { createPVCHandler as createHandler, updatePVCHandler as updateHandler } from '../../api/pvc.js'
import { useRouter } from 'vue-router'
const router = useRouter()
const props = defineProps({
  method: {
    type: String,
    default: 'Create'
  },
  item: {
    type: Object
  }
})
const data = reactive({
  clusterId: '',
  namespace: '',
  item: {// service数据结构定义
    apiVersion: 'v1',
    kind: 'PersistentVolumeClaim',
    metadata: {
      name: '',
      namespace: '',
      labels: {},
      annotations: {},
    },
    spec: {
      resources: {
        requests: {
          storage: '5Gi'
        }
      },
      volumeMode: 'Filesystem',
      storageClassName: '',
      accessModes: ['ReadWriteMany'],
    }
  },
  options: {
    volumeSourceSelected: null,
    labelList: [],
    annotationList: [],
    dataList: [],
    rules:{
      name: [
        {required: true, message: 'PVC名称必须值', trigger: 'blur'}
      ],
      capacity: [
        {required: true, message: 'pvc申请大小必须值', trigger: 'blur'}
      ],
      storageclass: [
        {required: true, message: '请选择存储类', trigger: 'blur'}
      ]
    },
    accessModes: [
      {
        label: '单节点读写',
        value: 'ReadWriteOnce'
      },
      {
        label: '多节点读写',
        value: 'ReadWriteMany'
      },
      {
        label: '多节点只读',
        value: 'ReadOnlyMany'
      },
      {
        label: '单Pod读写',
        value: 'ReadWriteOncePod'
      }
    ],
    volumeType: [
      {
        label: '文件系统',
        value: 'Filesystem'
      },
      {
        label: '块存储',
        value: 'Block'
      }
    ],
    claimType: [
      {
        value: 'pv',
        label: '静态申请'
      },
      {
        value: 'storageclass',
        label: '动态申请'
      },
    ],
    claimTypeSelected: 'storageclass',
    volumeSourceList: []
  }
})
const itemRef = ref()
const activeName = ref('basic')
const labelConfig = ref('labels')
const yamlContent = ref('')
const showDetail = ref(false)

const submitRollback = (msg) => {
  ElMessageBox.confirm(
    msg,
    '执行结果',
    {
      confirmButtonText: '查看列表',
      cancelButtonText: '返回',
      type: 'success',
      draggable: true,
    }
  ).then(() => {
    router.replace({
      path: '/pvc/list',// 跳转pvc列表页
      query: {
        clusterId: data.clusterId,
        namespace: data.namespace
      }
    })
  }).catch(() => {
    return
  })
}

const submitHandler = (tag) => {
  data.item.metadata.labels = list2Object(data.options.labelList)
  data.item.metadata.annotations = list2Object(data.options.annotationList)
  if(tag == 'yaml') { // json转yaml
    const yamlData = obj2Yaml(data.item)
    yamlContent.value = yamlData
    showDetail.value = true
  } else {
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: data.item
    }
    if (props.method != 'Update') {
      createHandler(postData).then((response) => {
        submitRollback(response.data.message)
      })
    } else {
      updateHandler(postData).then((response) => {
        console.log(props.method)
        submitRollback(response.data.message)
      })
    }
  }
}

const submit = (tag) => {
  itemRef.value.validate((valid) => {
    if(!valid){
      ElMessage({
        message: '请完善表单',
        type: "warning"
      })
    }else {
      submitHandler(tag)
    }
  })
  

}

const rollback = (clusterId, namespace) => {
  console.log('clusterId：', clusterId, 'namespace:', namespace)
  data.clusterId = clusterId
  data.namespace = namespace
  data.item.metadata.namespace = namespace
}

const claimTypeChanged = () => {
  data.options.volumeSourceSelected = null
  data.item.spec.storageClassName = ''
}

const visibleChanged = (visible) => {
  if(visible){
    listHandler(data.clusterId, data.namespace, data.options.claimTypeSelected).then((res) => {
    console.log("获取资源列表：", res.data.data.items)
    data.options.volumeSourceList = res.data.data.items
  })
  }
}

const volumeSourceChanged = (val) => {
  console.log(val)
  if(data.options.claimTypeSelected == 'pv') {
    data.item.spec.storageClassName = val.spec.storageClassName
  } else{
    data.item.spec.storageClassName = val.metadata.name
  }
}

onBeforeMount(() => {
  if(props.method != 'Create'){
    data.item = JSON.parse(JSON.stringify(props.item))
    data.options.labelList = object2List(data.item.metadata.labels)
    data.options.annotationList = object2List(data.item.metadata.annotations)
  }
})

const { options, item, clusterId, namespace } = toRefs(data)
</script>

<template>
  <CreateOrEditFrame
  :cluster-readonly="props.method=='Update'"
  :namespace-readonly="props.method=='Update'"
  @namespaceChanagedRollback="rollback"
  >
    <template #main>
      <el-form :model="item"
      center
      ref="itemRef"
      label-width="120"
      >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本配置" name="basic" style="height:360px">
            <el-row :gutter="5">
              <el-col :span="8">
                <el-form-item :rules="options.rules.name" label="pvc名称" prop="metadata.name" required>
                  <el-input :disabled="props.method == 'Update'" v-model="item.metadata.name" style="margin-left: 10px;width: 280px;"></el-input>
                </el-form-item>
              </el-col >
              <!-- 选择存储类型 -->
              <el-col :span="8" v-if="props.method != 'Update'">
                <el-form-item label="申请类型" prop="">
                  <el-select v-model="options.claimTypeSelected" @change="claimTypeChanged">
                    <el-option v-for="item in options.claimType" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8" v-if="props.method != 'Update'">
                <el-form-item :rules="options.rules.storageclass" label="选择资源" prop="spec.storageClassName" required>
                  <el-select
                  v-model="options.volumeSourceSelected"
                  @visible-change="visibleChanged"
                  @change="volumeSourceChanged"
                  value-key="metadata.name"
                  :placeholder="options.claimTypeSelected=='pv'?'请选择PV':'请选择storageClass'"
                  >
                    <el-option
                    v-for="item in options.volumeSourceList"
                    :key="item.metadata.name" :label="item.metadata.name" :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8" v-if="props.method == 'Update'">
                <el-form-item label="存储类" prop="">
                  <el-input :disabled="true" v-model="item.spec.storageClassName" style="margin-left: 10px;width: 280px;"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="5">
              <el-col :span="8">
                <el-form-item :rules="options.rules.capacity" label="存储空间" prop="spec.resources.requests.storage" required>
                  <el-input v-model="item.spec.resources.requests.storage" style="margin-left: 10px;width: 280px;"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="访问策略" prop="">
                  <el-select v-model="item.spec.accessModes" multiple collapse-tags placeholder="请选择访问策略">
                    <el-option v-for="item in options.accessModes" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="存储类型" prop="">
                  <el-select v-model="item.spec.volumeMode" placeholder="选择存储类型">
                    <el-option v-for="item in options.volumeType" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>


          <el-tab-pane label="注释及标签" name="labels" style="height:360px">
            <el-tabs v-model="labelConfig" tabPosition="left">
              <el-tab-pane label="标签配置" name="labels">
                <Table :list="options.labelList"></Table>
              </el-tab-pane>
              <el-tab-pane label="注解配置" name="annos">
                <Table :list="options.annotationList"></Table>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
        <span style="display: block;margin-top: 30px;" class="span-button">
          <el-button @click="submit('yaml')">yaml</el-button>
          <el-button type="primary" @click="submit()">{{ props.method=="Update"?"更新":"创建" }}</el-button>
        </span>
      </el-form>
    </template>
  </CreateOrEditFrame>
  <DialogYaml
  :cluster-id="clusterId"
  :namespace="namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => { showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
